package demo.security;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionMessage;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

import demo.security.JdbcTokenStoreConfiguration.JdbcTokenStoreCondition;


@Configuration
@ConditionalOnClass(DataSource.class)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
@Conditional(JdbcTokenStoreCondition.class)
public class JdbcTokenStoreConfiguration {
	
	@Autowired
	private DataSource dataSource;
	
	@Bean
	public TokenStore tokenStore() {
		return new JdbcTokenStore(this.dataSource);
	}
			
	static class JdbcTokenStoreCondition extends SpringBootCondition{

		@Override
		public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
			
			ConditionMessage.Builder message = ConditionMessage.forCondition("tokenStore Condition");
			
			if("JDBC".equals(context.getEnvironment().getProperty("demo.tokenStore"))){
				return ConditionOutcome.match(message.foundExactly("JDBC tokenStore"));
			}
			
			return ConditionOutcome.noMatch(message.didNotFind("JDBC tokenStore").atAll());
		}		
	}
}

